import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import DeviceList from '../views/device/DeviceList.vue'
import DeviceAdd from '../views/device/DeviceAdd.vue'
import UserList from '../views/user/UserList.vue'
import UserAdd from '../views/user/UserAdd.vue'
import TestConnection from '../views/TestConnection.vue'

// 路由守卫 - 检查用户是否已登录
function requireAuth(to, from, next) {
  const isAuthenticated = localStorage.getItem('isAuthenticated')
  if (to.path !== '/login' && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
}

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    beforeEnter: (to, from, next) => {
      // 如果已经登录，则重定向到主页
      const isAuthenticated = localStorage.getItem('isAuthenticated')
      if (isAuthenticated) {
        next('/home')
      } else {
        next()
      }
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    beforeEnter: requireAuth,
    children: [
      {
        path: '/devices',
        name: 'DeviceList',
        component: DeviceList
      },
      {
        path: '/device/add',
        name: 'DeviceAdd',
        component: DeviceAdd
      },
      {
        path: '/users',
        name: 'UserList',
        component: UserList
      },
      {
        path: '/user/add',
        name: 'UserAdd',
        component: UserAdd
      },
      {
        path: '/test-connection',
        name: 'TestConnection',
        component: TestConnection
      },
      // 添加默认子路由重定向
      {
        path: '',
        name: 'HomeRedirect',
        redirect: '/devices'
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局后置钩子，页面切换后滚动到顶部
router.afterEach((to, from) => {
  // 页面切换时滚动到顶部
  window.scrollTo(0, 0)
})

export default router